package com.muyi.util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/*
 *  自定义工具类
 * */
public class JDBCUtils {
    //构造方法私有
    private JDBCUtils() {
    }

    //成员变量
    private static String driver;
    private static String url;
    private static String userName;
    private static String passWord;

    static {
        Properties properties = new Properties();
        try {
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            //properties.load(new FileReader("src/jdbc.properties"));
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            userName = properties.getProperty("userName");
            passWord = properties.getProperty("passWord");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接的公共方法
     *
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        //将输入的用户名和密码与数据库中的用户信息做对比
        Class.forName(driver);
        //获取数据库连接对象
        Connection connection = DriverManager.getConnection(url, userName, passWord);
        return connection;
    }

    /**
     * 释放资源的公共方法
     *
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (null != resultSet) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (null != statement) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (null != connection) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
